using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

using System.Web;

using System.Runtime.InteropServices;
using HTTPAnalyzer;
using HTTPAnalyzerStd;

namespace BarnBuddyClient
{
    class BBCapture
    {
        HTTPAnalyzerStandAloneClass analyzer = null;
        public ArrayList data = null;

        public delegate void OnFirstItemCaptureDelegate();
        public event OnFirstItemCaptureDelegate OnFirstItemCapture;

        public delegate void OnItemCaptureDelegate();
        public event OnItemCaptureDelegate OnItemCapture;

        public const int BROWSER_IE = 1;
        public const int BROWSER_FIREFOX = 2;
        public const int BROWSER_ALL = 255;

        public BBCapture()
        {
            this.initData("all");
        }

        public BBCapture(string browsers)
        {
            this.initData(browsers);
        }

        private void initData(string browsers)
        {
            data = new ArrayList();

            analyzer = new HTTPAnalyzerStandAloneClass();
            analyzer.Visible = false;

            string[] browserArray = browsers.Split(',');
            int flag = 0;
            foreach (string br in browserArray)
            {
                string str = br.Trim().ToLower();
                switch (str)
                {
                    case "firefox": flag |= BROWSER_FIREFOX;break;
                    case "ie": flag |= BROWSER_IE;  break;
                    case "all": flag |= BROWSER_ALL;  break;
                }

            }

            if (flag == 0) flag = BROWSER_ALL;

            if ((flag & BROWSER_ALL) == BROWSER_ALL)
                analyzer.AttachAllSessions();
            else
            {

                if ((flag & BROWSER_IE) == BROWSER_IE)
                    analyzer.AttachProcessByName("IEXPLORE.EXE");

                if ((flag & BROWSER_FIREFOX) == BROWSER_FIREFOX)
                    analyzer.AttachProcessByName("firefox.exe");
            }

            analyzer.OnNewEntry += new ILogEvents_OnNewEntryEventHandler(analyzer_OnNewEntry);
            analyzer.OnUpdateEntry += new ILogEvents_OnUpdateEntryEventHandler(analyzer_OnUpdateEntry);

        }

        public void Start()
        {
            analyzer.Start();
        }

        public void Stop()
        {
            analyzer.Stop();
        }

        ~BBCapture() {
            analyzer = null;
        }

        void analyzer_OnUpdateEntry(ILogEntry Entry)
        {
            //Console.WriteLine("\r\nOnUpdateEntry: " + Entry.URL);
            if (Entry.IsComplete)
            {
                if (Entry.URL.Contains("farm_actionst2.php"))
                {
                    Hashtable item = new Hashtable();

                    string ownerId = "";
                    string methodName = "";

                    string postData = HttpUtility.bytes2String((byte[])Entry.Request.PostData);
                    postData = Uri.UnescapeDataString(postData);

                    Hashtable postParams = HttpUtility.extractPostData(postData);

                    if (postParams.ContainsKey("b"))
                    {
                        string jsonText = (string)postParams["b"];
                        jsonText = jsonText.Substring(1, jsonText.Length - 2);
                        Hashtable jsonObj = (Hashtable)JSON.JsonDecode(jsonText);

                        if (jsonObj.ContainsKey("ownerId"))
                        {
                            ownerId = (string)jsonObj["ownerId"];
                        }
                        if (jsonObj.ContainsKey("method"))
                        {
                            methodName = (string)jsonObj["method"];
                        }
                    }

                    if (ownerId != "" && (methodName.ToLower() == "getfarm" || methodName.ToLower() == "getinitdata")) {
                        item["ownerId"] = ownerId;
                        //Console.WriteLine(ownerId);

                        item["responseContent"] = HttpUtility.bytes2String((byte[])Entry.Content.Data);

                        data.Add(item);
                        if (data.Count == 1 && OnFirstItemCapture != null)
                        {
                            OnFirstItemCapture();
                        }
                        if (OnItemCapture != null) OnItemCapture();
                    }
                }
            }
        }

        void analyzer_OnNewEntry(ILogEntry Entry, ref bool DiscardIt)
        {
            //Console.WriteLine("\r\nOnNewEntry: " + Entry.URL);            
        }

        private string getOwnerId(string postData)
        {
            string ownerId = "";

            Hashtable postParams = HttpUtility.extractPostData(postData);

            if (postParams.ContainsKey("b"))
            {
                string jsonText = (string)postParams["b"];
                jsonText = jsonText.Substring(1, jsonText.Length - 2);
                Hashtable jsonObj = (Hashtable)JSON.JsonDecode(jsonText);

                if (jsonObj.ContainsKey("ownerId"))
                {
                    ownerId = (string)jsonObj["ownerId"];
                }
            }

            return ownerId;
        }

    }
}
